<?php

namespace app\admin\controller;

use addons\jiezicommon\service\Tools;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\common\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Order;
        $this->view->assign("payStatusList", $this->model->getPayStatusList());
        $this->view->assign("shipStatusList", $this->model->getShipStatusList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("confirmList", $this->model->getConfirmList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user','jieziarea'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('user')->visible(['username']);
				$row->getRelation('jieziarea')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 修改支付状态
     * @param null $ids
     * @param null $status
     * @throws \think\exception\DbException
     */
    public function set_status($ids = null, $status = null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($status){
            if($status == 2){
                if($row['status'] != 1){
                    $this->error('状态应为待支付');
                }
                $row->save(['status'=>2, 'pay_status' => 2, 'paytime' => time()]);
                $this->success();
            }
            if($status == 1){
                if($row['status'] != 2){
                    $this->error('状态应为已支付');
                }
                $row->save(['status'=>1, 'pay_status' => 1]);
                $this->success();
            }
        }
    }

    /**
     * 发起退款
     * @param null $ids
     * @throws \think\exception\DbException
     */
    public function refund($ids = null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($row['status'] != 2){
            $this->error('状态应为已支付');
        }
        if($row['transaction_id']) {
            $myparams['order_id'] = $row['id'];
            $myparams['out_trade_no'] = $row['out_trade_no'];
            $myparams['total_fee'] = number_format($row['order_amount'], 2, '.', '');
            $myparams['refund_fee'] = number_format($row['order_amount'], 2, '.', '');

            $resl = \addons\jiezicommon\service\Tools::refund($myparams);

            if(!empty($resl['return_code']) && $resl['return_code'] != 'SUCCESS'){
                //发起退款-失败
                $this->error('退款失败！' . $resl['return_msg']);
            }
            if (!empty($resl['result_code']) && $resl['result_code'] == 'SUCCESS') {
                $this->success('已发出退款请求，请稍后刷新');
            } else {
                //发起退款-失败
                $this->error('退款失败！！' . $resl['err_code_des']);
            }
            /*if ($row['paytype'] == 'alipay') {
                $order = [
                    'out_trade_no' => $row['sn'],
                    'refund_amount' => $row['money'],
                    '_action' => 'app', // 退款 APP 订单
                ];
                $result = \Yansongda\Pay\Pay::alipay($config)->refund($order);
//            var_dump($result);die;
                if ($result->code != '10000') {
                    $this->error($result->sub_msg);
                } else {
                    if ($result->fund_change == 'N') {
                        //重复提交时，直接修改数据库
                        $row->save(['status' => 3, 'refundtime' => time()]);
                        //设置押金=0
                        if($row['type'] == 1) {
                            \app\common\model\Companion::where('user_id', $row['user_id'])->update(['deposit' => 0, 'apply_order_id' => 0]);
                        }else{
                            \app\common\model\Agent::where('user_id', $row['user_id'])->update(['deposit' => 0]);
                        }
                        $this->success('操作成功');
                    } else {
                        $this->success('已发出退款请求，请稍后刷新');
                    }
                }
            }*/
        }else{
            $row->save(['status' => 3, 'canceltime' => time()]);
            $this->success();
        }
    }

    /**
     * 发货
     *
     * @param $ids
     * @return string
     * @throws \think\Exception
     */
    public function shipping($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
//            var_dump(self::is_trade_management_confirmation_completed());

            $list = \app\common\model\OrderItems::where('order_id', $ids)->select();
            $goods = [];
            foreach ($list as $t){
                $images = $t['images'] ? Tools::str2arr($t['images'], ',', 'cdnurl', true, [true]) : [];
                $image = !empty($images[0]) ? $images[0] : '';
                $goods[] = [
                    'name' => $t['name'],
                    'spes' => $t['spes'],
                    'price' => $t['price'],
                    'images' => $images,
                    'image' => $image,
                    'nums' => $t['nums'],
                ];
            }
            $row['goods'] = $goods;
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $params['pay_status'] = 2;
            $params['shiptime'] = time();
            $result = $row->allowField(true)->save($params);
//            $result = true;
            //小程序发货
            /*$res = self::is_trade_managed();
            $res2 = self::is_trade_management_confirmation_completed();
            if(isset($res['errcode']) && !$res['errcode'] && $res['is_trade_managed']){
                if(isset($res2['errcode']) && !$res2['errcode'] && $res2['completed']){
                    $config = Tools::getInstance()->getMiniProgram();
                    $goods_list = \app\common\model\OrderItems::where('order_id', $ids)->select();
                    $shipping_list = [];
                    foreach ($goods_list as $goods){
                        $shipping_list[] = [
                            'tracking_no' => $params['ship_c_sn'],//物流单号，物流快递发货时必填
                            'express_company' => $params['ship_c_code'],//
                            'item_desc' => $goods['name'] . '*' . $goods['nums'],
                            'contact' => [
                                'receiver_contact' => substr_replace($params['ship_mobile'], '****', -8, 4),
                            ],
                        ];
                    }
                    $openid = \addons\third\model\Third::where('user_id', $row['user_id'])->value('openid');
                    $datas = [
                        'order_key' => [
                            'order_number_type' => 1,//枚举值1，使用下单商户号和商户侧单号；枚举值2，使用微信支付单号。
                            'mchid' => $config['mch_id'],
                            'out_trade_no' => $row['out_trade_no'],
                        ],
                        'logistics_type' => 1,//物流模式，发货方式枚举值：1、实体物流配送采用快递公司进行实体物流配送形式 2、同城配送 3、虚拟商品，虚拟商品，例如话费充值，点卡等，无实体配送形式 4、用户自提
                        'delivery_mode' => 1,//发货模式，发货模式枚举值：1、UNIFIED_DELIVERY（统一发货）2、SPLIT_DELIVERY（分拆发货） 示例值: UNIFIED_DELIVERY
                        'shipping_list' => $shipping_list,
                        'upload_time' => date('Y-m-d\TH:i:sP'),
                        'payer' => [
                            'openid' => $row['openid'] ? $row['openid'] : $openid,
                        ],
                    ];
//                    var_dump($datas);die;
                    $res3 = self::upload_shipping_info($datas);
                    if(!empty($res3['errcode'])){
                        Db::rollback();
                        $this->error($res3['errmsg']);
//                        throw new \Exception($res3['errmsg']);
                    }
//                    var_dump($res3);die;
                }
            }*/
            $sn = $row['order_sn'];
            //给用户添加积分=订单总额
            $row['order_amount'] > 0 && \app\common\model\User::points(1, $sn, 0, $row['order_amount'], $row['user_id'], '购买', $this->auth->id);
            //是否已经给予父级宝豆parent_speed_order_id
            $user = \app\common\model\User::where('id', $row['user_id'])->find();
            
            if($user['parent_id'] && !$user['parent_speed_order_id']){
                //父级宝豆=订单总额的百分比
                $cargo_value = $row['order_amount'] * 0.1;
                $cargo_value > 0 && \app\common\model\User::cargo_value(2, $sn, 0, $cargo_value, $user['parent_id'], '邀请', $this->auth->id);
                $user['parent_speed_order_id'] = $ids;
                $user->save();
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 收货
     *
     * @param $ids
     * @return string
     * @throws \think\Exception
     */
    public function receive($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
//            var_dump(self::is_trade_management_confirmation_completed());
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
//            $this->error(__('Parameter %s can not be empty', ''));
        }
        if($row['status'] != 3){
            $this->error('状态异常');
        }
//        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $params['status'] = 4;
            $params['confirm'] = 2;
            $params['confirmtime'] = time();
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 详细
     *
     * @param $ids
     * @return string
     * @throws \think\Exception
     */
    public function info($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        $list = \app\common\model\OrderItems::where('order_id', $ids)->select();
        $goods = [];
        foreach ($list as $t){
            $images = $t['images'] ? Tools::str2arr($t['images'], ',', 'cdnurl', true, [true]) : [];
            $image = !empty($images[0]) ? $images[0] : '';
            $goods[] = [
                'name' => $t['name'],
                'spes' => $t['spes'],
                'price' => $t['price'],
                'images' => $images,
                'image' => $image,
                'nums' => $t['nums'],
            ];
        }
        $row['goods'] = $goods;
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    /**
     * 获取快递数据
     * @return mixed
     */
    public function get_wx_deliver_list_selectpage(){
        $return_data = self::get_wx_delivery_list();
        if(empty($return_data['code'])){
            $this->error($return_data['msg']);
        }
        $return_data['total'] = count($return_data['list']);
        return json($return_data);
        var_dump($return_data);die;
        $this->success('获取快递数据成功', null, $return_data);
    }



    /**
     * 微信-获取运力id列表get_delivery_list
     * @return mixed
     */
    public static function get_wx_delivery_list(){
        $config = Tools::getInstance()->getMiniProgram();
        $return_data = [
            'code' => 1,
            'total' => 0,
            'list' => [],
        ];
        try {
            $app = \EasyWeChat\Factory::miniProgram($config);
            $list = $app->express->listProviders();
//            var_dump($list);
            $return_data['total'] = $list['count'];
            $return_data['list'] = $list['data'];
        }catch (\Exception $e){
            $return_data['code'] = 0;
            $return_data['msg'] = $e->getMessage();
        }
        return $return_data;
    }

    public static function is_trade_managed(){
        $config = Tools::getInstance()->getMiniProgram();
        $app = \EasyWeChat\Factory::miniProgram($config);
        $res = $app->express->httpPostJson('wxa/sec/order/is_trade_managed', ['appid' => $config['app_id']]);
        return $res;
    }

    public static function is_trade_management_confirmation_completed(){
        $config = Tools::getInstance()->getMiniProgram();
        $app = \EasyWeChat\Factory::miniProgram($config);
        $res = $app->express->httpPostJson('wxa/sec/order/is_trade_management_confirmation_completed', ['appid' => $config['app_id']]);
        return $res;
    }

    public static function upload_shipping_info($data){
        $config = Tools::getInstance()->getMiniProgram();
        $app = \EasyWeChat\Factory::miniProgram($config);
        $res = $app->express->httpPostJson('wxa/sec/order/upload_shipping_info', $data);
        return $res;
    }
}
